//----------------------------------------------------------------------------------------------------------------------
// Copyright (c) 2012 James Whitworth
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the \"Software\"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//----------------------------------------------------------------------------------------------------------------------

//----------------------------------------------------------------------------------------------------------------------
// Variable argument format
// function vformat(format_string, args)
//----------------------------------------------------------------------------------------------------------------------
function vformat(formatstr, args)
{
  assert(type(args) == "array")

  // no way of passing vargs through to another function so have to do this lame switch
  //
  switch(args.len())
  {
  case 0:
    // this makes sure there are no missing args.
    //
    return format(formatstr)
  case 1:
    return format(formatstr, args[0])
  case 2:
    return format(formatstr, args[0], args[1])
  case 3:
    return format(formatstr, args[0], args[1], args[2])
  case 4:
    return format(formatstr, args[0], args[1], args[2], args[3])
  case 5:
    return format(formatstr, args[0], args[1], args[2], args[3], args[4])
  case 6:
    return format(formatstr, args[0], args[1], args[2], args[3], args[4], args[5])
  case 7:
    return format(formatstr, args[0], args[1], args[2], args[3], args[4], args[5], args[6])
  case 8:
    return format(formatstr, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7])
  default:
    throw("too many arguments to fprint")
  }
}

//----------------------------------------------------------------------------------------------------------------------
// Base stream class for serialising text output.
//----------------------------------------------------------------------------------------------------------------------
class OutputStream
{
  indent_string = null
  should_indent = null

  constructor()
  {
    indent_string = ""
    should_indent = false
  }

  // Serializes a formatted string to the output
  //
  function write(formatstr, ...)
  {
    if (should_indent)
    {
      internal_write(indent_string)
      should_indent = false
    }

    local str = vformat(formatstr, vargv)
    internal_write(str)
  }

  // starts a new line with the correct indentation
  //
  function new_line()
  {
    internal_write("\n")
    should_indent = true
  }

  // Adds a separator to break up code in to sections
  //
  function add_separator()
  {
    internal_write("//----------------------------------------------------------------------------------------------------------------------")
    new_line()
  }

  // indent the text being written out, used when changing scope
  //
  function indent()
  {
    indent_string = indent_string + "  "
  }

  // opposite of indent
  //
  function outdent()
  {
    local length = indent_string.len()
    assert(length >= 2)
    indent_string = indent_string.slice(0, length - 2)
  }

  // actual function that serialises a string
  //
  function internal_write(str)
  {
    print(str)
  }
}

//----------------------------------------------------------------------------------------------------------------------
// Derived stream class that outputs to a file
//----------------------------------------------------------------------------------------------------------------------
class OutputFileStream extends OutputStream
{
  output_file = null
  
  constructor(filename)
  {
    base.constructor()
    output_file = file(filename, "wb")
  }

  function internal_write(str)
  {
    if (type(str) == "string")
    {
      local length = str.len()
      for (local i = 0; i != length; ++i)
      {
        local ascii_char = str.slice(i, i + 1)

        if (ascii_char in ascii_map)
        {
          // make sure we output windows line endings: /r/n
          //
          if (ascii_char == "\n")
          {
            local previous_ascii_char = str.slice(i - 1, i)
            if (previous_ascii_char && previous_ascii_char != "\r")
            {
              local ascii_value = ascii_map["\r"]
              output_file.writen(ascii_value, 'b')
            }
          }

          local ascii_value = ascii_map[ascii_char]
          output_file.writen(ascii_value, 'b')
        }
        else
        {
          error(format("error serializing string '%s' at index '%d'", str, i))
        }
      }
    }
  }

  // this maps from the ascii character to the binary character value
  // as squirrel isn't great at ascii file io, this is the only way to do it
  //
  ascii_map = {
    ["\0"] = 0,
    ["\t"] = 9,
    ["\n"] = 10,
    ["\v"] = 11,
    ["\f"] = 12,
    ["\r"] = 13,
    [" "] = 32,
    ["!"] = 33,
    ["\""] = 34,
    ["#"] = 35,
    ["$"] = 36,
    ["%"] = 37,
    ["&"] = 38,
    ["'"] = 39,
    ["("] = 40,
    [")"] = 41,
    ["*"] = 42,
    ["+"] = 43,
    [","] = 44,
    ["-"] = 45,
    ["."] = 46,
    ["/"] = 47,
    ["0"] = 48,
    ["1"] = 49,
    ["2"] = 50,
    ["3"] = 51,
    ["4"] = 52,
    ["5"] = 53,
    ["6"] = 54,
    ["7"] = 55,
    ["8"] = 56,
    ["9"] = 57,
    [":"] = 58,
    [";"] = 59,
    ["<"] = 60,
    ["="] = 61,
    [">"] = 62,
    ["?"] = 63,
    ["@"] = 64,
    ["A"] = 65,
    ["B"] = 66,
    ["C"] = 67,
    ["D"] = 68,
    ["E"] = 69,
    ["F"] = 70,
    ["G"] = 71,
    ["H"] = 72,
    ["I"] = 73,
    ["J"] = 74,
    ["K"] = 75,
    ["L"] = 76,
    ["M"] = 77,
    ["N"] = 78,
    ["O"] = 79,
    ["P"] = 80,
    ["Q"] = 81,
    ["R"] = 82,
    ["S"] = 83,
    ["T"] = 84,
    ["U"] = 85,
    ["V"] = 86,
    ["W"] = 87,
    ["X"] = 88,
    ["Y"] = 89,
    ["Z"] = 90,
    ["["] = 91,
    ["\\"] = 92,
    ["]"] = 93,
    ["^"] = 94,
    ["_"] = 95,
    ["`"] = 96,
    ["a"] = 97,
    ["b"] = 98,
    ["c"] = 99,
    ["d"] = 100,
    ["e"] = 101,
    ["f"] = 102,
    ["g"] = 103,
    ["h"] = 104,
    ["i"] = 105,
    ["j"] = 106,
    ["k"] = 107,
    ["l"] = 108,
    ["m"] = 109,
    ["n"] = 110,
    ["o"] = 111,
    ["p"] = 112,
    ["q"] = 113,
    ["r"] = 114,
    ["s"] = 115,
    ["t"] = 116,
    ["u"] = 117,
    ["v"] = 118,
    ["w"] = 119,
    ["x"] = 120,
    ["y"] = 121,
    ["z"] = 122,
    ["{"] = 123,
    ["|"] = 124,
    ["}"] = 125,
    ["~"] = 126,
  }
}